package com.dwxt.cdms.service.wx;

import com.alibaba.fastjson.JSONObject;
import com.dwxt.cdms.api.common.utils.DateUtil;
import com.dwxt.cdms.dao.CustomerMapper;
import com.dwxt.cdms.dao.HealthWarnRecordMapper;
import com.dwxt.cdms.dao.WxBindMapper;
import com.dwxt.cdms.entity.*;
import com.dwxt.cdms.service.RelationService;
import com.dwxt.cdms.util.wx.WxUtil;
import com.dwxt.common.util.JsonUtils;
import com.dwxt.common.util.OkHttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Slf4j
@Service
public class WxMessageService {

    static final String template_id_cl = "Z43mRCS35XXZnEotdOTvlBZ3EQSIQMbp-Zw387SNVxc";
    static final String template_id_report = "Ju-NqwokQ_INZh5TUkthKjm8EiFHkNsLF-ffcLKDPzk";
    static final String template_id_warn = "atOvaydG8pzM5ONul406UzTYtW3I_z3fXpWYKhsoNf4";

    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private HealthWarnRecordMapper healthWarnRecordMapper;
    @Autowired
    private RelationService relationService;
    @Autowired
    private WxBindMapper wxBindMapper;

    public void sendWarnMessageToGzh(Integer customerId, String detail, Date date, String category) {
        Customer customer = customerMapper.selectByPrimaryKey(customerId);
        HashMap<String, Object> param = new HashMap<>();
        JSONObject top = new JSONObject();
        JSONObject first = new JSONObject();
        String firstStr = "您收到一条【" + detail + "】提醒";
        first.put("value", firstStr);
        top.put("first", first);
        //发送时间
        JSONObject keyword1 = new JSONObject();
        String time = DateUtil.parseStr(date, DateUtil.FMT_YYYYMMDD_HHMMSS);
        keyword1.put("value", time);
        top.put("keyword1", keyword1);
        //异常描述
        JSONObject keyword2 = new JSONObject();
        String name = StringUtils.isNotBlank(customer.getName()) ? customer.getName() : customer.getPhone();
        String content = "来自【" + name + "】的" + category+"的"+detail;
        keyword2.put("value", content);
        top.put("keyword2", keyword2);
        //remark
        JSONObject remark = new JSONObject();
        remark.put("value", "如需帮助，请拨打24小时人工守护中心电话（968008）");
        top.put("remark", remark);
        WxBind wxBind1 = new WxBind();
        wxBind1.setStatus(1);
        wxBind1.setCustomerId(customer.getId());
        WxBind wxBind11 = wxBindMapper.selectOne(wxBind1);
        param.put("template_id", template_id_warn);
        HashMap<String, String> header = new HashMap<>();
        header.put("Content-Type", "application/json");
        //本人推送
        if (wxBind11 != null && StringUtils.isNotBlank(wxBind11.getOpenid())) {
            param.put("touser", wxBind11.getOpenid());
            param.put("data", top);
            if (param.get("data") != null) {
                String s = OkHttpUtils.jsonPost("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + WxUtil.getAccessToken(), JsonUtils.objectToJson(param), header);
                log.info("公众号消息发送参数:" + param + "返回：" + s);
            }
        }
        //关联人推送
        List<Relation> relations = relationService.selectOnlyManagerCustomer(customer.getId());
        for (Relation relation : relations) {
            WxBind wxBind2 = new WxBind();
            wxBind2.setStatus(1);
            wxBind2.setCustomerId(relation.getCustomerId());
            WxBind wxBind22 = wxBindMapper.selectOne(wxBind2);
            if (wxBind22 != null && StringUtils.isNotBlank(wxBind22.getOpenid())) {
                //跳过自己
                if (customer.getId() == wxBind22.getCustomerId()) {
                    continue;
                }
                param.put("touser", wxBind22.getOpenid());
                if (param.get("data") != null) {
                    String s = OkHttpUtils.jsonPost("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + WxUtil.getAccessToken(), JsonUtils.objectToJson(param), header);
                    log.info("公众号消息发送参数:" + param + "返回：" + s);
                }
            }
        }
    }

    /**
     * @Description: 公众号发送处理结果消息
     * @Param [customer, detail, date, worker, handleType]
     * @Return void
     * @Author chendq
     * @Date 2022/2/21
     **/
    public void sendHandleMessageToGzh(Customer customer, String detail, Date date, String worker, String handleType) {

        HashMap<String, Object> param = new HashMap<>();
        JSONObject top = new JSONObject();
        JSONObject first = new JSONObject();
        String firstStr = "您收到一条【" + detail + "】报警处理结果提醒";
        first.put("value", firstStr);
        top.put("first", first);
        //家人姓名
        JSONObject keyword1 = new JSONObject();
        String name = StringUtils.isNotBlank(customer.getName()) ? customer.getName() : customer.getPhone();
        keyword1.put("value", name);
        top.put("keyword1", keyword1);
        //处理时间
        JSONObject keyword2 = new JSONObject();
        String time = DateUtil.parseStr(date, DateUtil.FMT_YYYYMMDD_HHMMSS);
        keyword2.put("value", time);
        top.put("keyword2", keyword2);
        //处理人员
        JSONObject keyword3 = new JSONObject();
        keyword3.put("value", worker);
        top.put("keyword3", keyword3);
        //处理方式
        JSONObject keyword4 = new JSONObject();
        keyword4.put("value", handleType);
        top.put("keyword4", keyword4);
        //remark
        JSONObject remark = new JSONObject();
        remark.put("value", "如需帮助，请拨打24小时人工守护中心电话（968008）");
        top.put("remark", remark);
        WxBind wxBind1 = new WxBind();
        wxBind1.setStatus(1);
        wxBind1.setCustomerId(customer.getId());
        WxBind wxBind11 = wxBindMapper.selectOne(wxBind1);
        param.put("template_id", template_id_cl);
        HashMap<String, String> header = new HashMap<>();
        header.put("Content-Type", "application/json");
        //本人推送
        if (wxBind11 != null && StringUtils.isNotBlank(wxBind11.getOpenid())) {
            param.put("touser", wxBind11.getOpenid());
            param.put("data", top);
            if (param.get("data") != null) {
                String s = OkHttpUtils.jsonPost("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + WxUtil.getAccessToken(), JsonUtils.objectToJson(param), header);
                log.info("公众号消息发送参数:" + param + "返回：" + s);
            }
        }
        //关联人推送
        List<Relation> relations = relationService.selectOnlyManagerCustomer(customer.getId());
        for (Relation relation : relations) {
            WxBind wxBind2 = new WxBind();
            wxBind2.setStatus(1);
            wxBind2.setCustomerId(relation.getCustomerId());
            WxBind wxBind22 = wxBindMapper.selectOne(wxBind2);
            if (wxBind22 != null && StringUtils.isNotBlank(wxBind22.getOpenid())) {
                //跳过自己
                if (customer.getId().equals(wxBind22.getCustomerId())) {
                    continue;
                }
                param.put("touser", wxBind22.getOpenid());
                if (param.get("data") != null) {
                    String s = OkHttpUtils.jsonPost("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + WxUtil.getAccessToken(), JsonUtils.objectToJson(param), header);
                    log.info("公众号消息发送参数:" + param + "返回：" + s);
                }
            }
        }
    }


    /**
     * @Description: 小程序发送处理结果消息
     * @Param [handleType, customer, detail, createTime]
     * @Return void
     * @Author chendq
     * @Date 2022/2/21
     **/
    public void sendHandleMessageToMinApp(String handleType, Customer customer, String detail, Date createTime) {
        String content = "您在" + DateUtil.parseStr(createTime, DateUtil.FMT_YYYYMMDD_HHMMSS) + "产生的【" + detail + "】报警信息已通过" + handleType + "方式处理完成。";
        HealthMessage msg = new HealthMessage();
        msg.setType("报警处理通知");
        msg.setContent(content);
        msg.setCustomerId(customer.getId());
        msg.setId(UUID.randomUUID().toString());
        msg.setCrateTime(new Date());
        healthWarnRecordMapper.insertMessage(msg);
        //小程序消息通知关联人
        List<Relation> relations = relationService.selectOnlyManagerCustomer(customer.getId());
        String name = StringUtils.isNotBlank(customer.getName()) ? customer.getName() : customer.getPhone();
        String content1 = "您的关联人【" + name + "】在" + DateUtil.parseStr(createTime, DateUtil.FMT_YYYYMMDD_HHMMSS) + "产生的【" + detail + "】报警信息已通过" + handleType + "方式处理完成。";
        for (Relation relation : relations) {
            msg.setContent(content1);
            msg.setCustomerId(relation.getCustomerId());
            msg.setId(UUID.randomUUID().toString());
            healthWarnRecordMapper.insertMessage(msg);
        }
    }


    /**
     * @Description: 公众号发送月度健康报告
     * @Param [report, customer]
     * @Return void
     * @Author chendq
     * @Date 2022/2/21
     **/
    public void sendMonthReportToGzh(HealthReport report, Customer customer) {
        try {
            HashMap<String, Object> param = new HashMap<>();
            JSONObject top = new JSONObject();
            JSONObject first = new JSONObject();
            String firstStr = "月度报告已生成，快去看看您的健康情况吧";
            first.put("value", firstStr);
            top.put("first", first);
            //检测码
            JSONObject keyword1 = new JSONObject();
            String reportId = report.getId();
            keyword1.put("value", reportId);
            top.put("keyword1", keyword1);
            //报告生成时间
            JSONObject keyword2 = new JSONObject();
            Calendar cal_1 = Calendar.getInstance();
            cal_1.add(Calendar.MONTH, -1);
            cal_1.set(Calendar.DAY_OF_MONTH, 1);
            String firstDay = DateUtil.parseStr(cal_1.getTime(), DateUtil.FMT_YYYYMMDD);
            Calendar cale = Calendar.getInstance();
            cale.set(Calendar.DAY_OF_MONTH, 0);
            String lastDay = DateUtil.parseStr(cale.getTime(), DateUtil.FMT_YYYYMMDD);
            String time = firstDay + "-" + lastDay;
            keyword2.put("value", time);
            top.put("keyword2", keyword2);
            //remark
            JSONObject remark = new JSONObject();
            remark.put("value", "点击“查看详情”了解详细月度健康报告");
            top.put("remark", remark);
            WxBind wxBind1 = new WxBind();
            wxBind1.setStatus(1);
            wxBind1.setCustomerId(customer.getId());
            WxBind wxBind11 = wxBindMapper.selectOne(wxBind1);
            param.put("template_id", template_id_report);
            param.put("url", "https://min.cqzhty.com/wssq/abx/index.html?id=" + customer.getId());
            HashMap<String, String> header = new HashMap<>();
            header.put("Content-Type", "application/json");
            //本人推送
            if (wxBind11 != null && StringUtils.isNotBlank(wxBind11.getOpenid())) {
                param.put("touser", wxBind11.getOpenid());
                param.put("data", top);
                String s = OkHttpUtils.jsonPost("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + WxUtil.getAccessToken(), JsonUtils.objectToJson(param), header);
                log.info("公众号消息发送参数:" + param + "返回：" + s);
            }
            //关联人推送
            List<Relation> relations = relationService.selectOnlyManagerCustomer(customer.getId());
            for (Relation relation : relations) {
                WxBind wxBind2 = new WxBind();
                wxBind2.setStatus(1);
                wxBind2.setCustomerId(relation.getCustomerId());
                WxBind wxBind22 = wxBindMapper.selectOne(wxBind2);
                if (wxBind22 != null && StringUtils.isNotBlank(wxBind22.getOpenid())) {
                    String firstStr1 = "您的关联人月度报告已生成，快去看看TA的健康情况吧";
                    first.put("value", firstStr1);
                    top.put("first", first);
                    param.put("data", top);
                    param.put("touser", wxBind22.getOpenid());
                    String s = OkHttpUtils.jsonPost("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + WxUtil.getAccessToken(), JsonUtils.objectToJson(param), header);
                    log.info("公众号消息发送参数:" + param + "返回：" + s);
                }
            }

        } catch (Exception e) {
            log.error("发送微信消息失败：" + e.toString());
        }
    }
}
